from django.shortcuts import render
from django.db import connection


from rest_framework.decorators import api_view
from rest_framework.response import Response

import datetime
# Create your views here.

# ------ 登入验证-----------
@api_view(["get"])
def login_check(request):
    '''
    :param request:
    :return: 验证结果
    '''
    acc = request.GET.get("acc")
    pd = request.GET.get("pd")

    # 获取游标，拿到对象
    with connection.cursor() as cursor:
        cursor.execute("select * from user where acc='" +acc + "'")
        user = cursor.fetchone()
        user =dict(zip([desc[0] for desc in cursor.description],user))

    if cursor.rowcount < 1:
        return Response({"state":"failure","problem":"acc"})
    if str(pd) != user["password"]:
        return Response({"state":"failure","problem":"pd"})
    return Response({"state":"success","id":user["id"],"name":user["name"]})

# ------ 注册验证-----------
@api_view(["get"])
def register_check(request):
    acc = request.GET.get("acc")
    pd = request.GET.get("pd")
    motto = request.GET.get("motto")
    name = request.GET.get("name")

    # 今天的日期
    today = datetime.date.today().strftime("%Y-%m-%d")
    print(today)

    userQuerySql = '''
        select * from user 
        where acc=%s
    '''%(acc)
    userRegisterSql = '''
        insert
        into user(name,acc,password,motto,register_date) 
        values('%s','%s','%s','%s','%s')
    '''%(name,acc,pd,motto,today)
    with connection.cursor() as cursor:
        cursor.execute(userQuerySql)
        if cursor.rowcount == 0:
            cursor.execute(userRegisterSql)
            return Response({"state":"success"})
    return Response({"state":"failure"})


# ------ 首页初试请求 -------
@api_view(["get"])
def index(request):
    hotArticlesSql= ''' select article.id,title,read_num,user.name name
                        from article,user 
                        where article.user_id = user.id
                        order by read_num desc
                        limit 10 '''
    latestArticlesSql = ''' select article.*,user.name name
                            from article,user 
                            where article.user_id = user.id
                            order by created_date desc '''
    with connection.cursor() as cursor:
        # 查询最新文章
        cursor.execute(latestArticlesSql)
        latestArticles = []
        for row in cursor.fetchall():
            latestArticles.append(dict(zip([desc[0] for desc in cursor.description],row)))

        # 查询前十篇人们文章
        cursor.execute(hotArticlesSql)
        hotArticles = []
        for row in cursor.fetchall():
            hotArticles.append(dict(zip([desc[0] for desc in cursor.description],row)))

    articleNum = len(latestArticles) # 总的文章数量
    numOfEveryPage = 6 # 每页有多少文章
    pageNum = 1 if articleNum > 0 else 0 # 当前页码
    # 总页码
    totalNum = articleNum // numOfEveryPage if articleNum % numOfEveryPage == 0 else articleNum // numOfEveryPage+1

    if articleNum > numOfEveryPage:
        latestArticles = latestArticles[0:6]

    return Response({"latestArticles":latestArticles,
                        "hotArticles":hotArticles,
                        "pageNum":pageNum,
                        "totalNum":totalNum
                    })

# ------- 换页和搜索 --------
@api_view(["get"])
def change_page(request):
    pageNum = int(request.GET.get("pageNum",0))
    keyword = request.GET.get("keyword",None)
    tag = request.GET.get("tag",None)

    # 首页初试请求换页
    if not keyword and not tag:
        sql = "select article.*,user.name name from article,user where article.user_id = user.id order by created_date desc"
    elif keyword:
        sql= "select article.*,user.name name from article,user where article.user_id = user.id and (tag like '%%%%" + keyword + "%%%%' or " + "title like '%%%%" + keyword + "%%%%' or " + "content like '%%%%" + keyword + "%%%%')" +" order by read_num desc"
    elif tag:
        sql = "select article.*,user.name name from article,user where article.user_id = user.id and  tag='"+tag+"' order by read_num desc"

    numOfEveryPage = 6
    with connection.cursor() as cursor:
        cursor.execute(sql)
        count = cursor.rowcount # 总文章数量
        print("count:"+str(count))
        start = (pageNum-1) * numOfEveryPage
        print("start:"+str(start))
        end = count if start + numOfEveryPage > count else  start + numOfEveryPage
        print("end:"+str(end))
        articles = []
        # 返回字典
        for row in cursor.fetchall()[start:end]:
            articles.append(dict(zip([desc[0] for desc in cursor.description],row)))

        # 总页数
        totalNum = count // numOfEveryPage if count % numOfEveryPage == 0 else count // numOfEveryPage+1

        if count == 0:
            pageNum = 0

    return Response({"pageNum":pageNum,"totalNum":totalNum,"articles":articles})

# -------- 个人信息 -------------
from api.tools.articles import articles_of_user
@api_view(["get"])
def profile(request):
    userId = request.GET.get("id",5)

    # ----用户信息----
    authorInfoSql = "select id,name,motto,register_date from user where id=" + str(userId)

    with connection.cursor() as cursor:
        cursor.execute(authorInfoSql)
        if cursor.rowcount == 0:
            return Response({"state":"不存在该用户"})
        author_info = dict(zip([desc[0] for desc in cursor.description],cursor.fetchone()))


    # ---- 用户文章 -----
    temp = articles_of_user(userId)
    articles = temp["articles"]

    # ---- 原创文章梳理和阅读总数----

    author_info["readNumTotal"] = temp["read_num_total"]
    author_info["originalArticleNum"] = temp["original_article_num"]

    return Response({"authorInfo": author_info,"articles":articles})



# ------ 写文章 ------
@api_view(["get"])
def write(request):
    id = int(request.GET.get("userId"))
    title = request.GET.get("title")
    content = request.GET.get("content")
    tag = request.GET.get("tag")
    is_original = int(request.GET.get("isOriginal",1))
    print(is_original)
    is_public = int(request.GET.get("isPublic",1))

    today = datetime.date.today().strftime("%Y-%m-%d")
    saveArticle='''
        insert 
        into article(title,content,update_date,created_date,tag,is_public,is_original,user_id,read_num)
        values('%s', '%s','%s','%s','%s',%d,%d,%d,0)
    '''%(title,content,today,today,tag,is_public,is_original,id)

    with connection.cursor() as cursor:
        cursor.execute(saveArticle)

    return Response({"state":"200"})

# ------- 查看文章 -------
@api_view(["get"])
def request_for_detail(request):
    id = request.GET.get("id")
    articleI_info_sql = "select * from article where id="+ str(id)

    # 返回数据
    data = {}

    # -----文章信息-----
    with connection.cursor() as cursor:
        cursor.execute(articleI_info_sql)
        # 文章不为空
        if cursor.rowcount > 0 :
            result = cursor.fetchone()
            article_info=dict(zip([desc[0] for desc in cursor.description],result))

            # 文章阅读数量加1
            read_num_incr_sql="update article set read_num=read_num+1 where id="+str(id)
            cursor.execute(read_num_incr_sql)

            article_info["read_num"] += 1
        else:
            article_info = {}



    # ------用户信息------
    user_id = article_info["user_id"]
    user_info_sql = "select * from user where id=%d"%user_id
    with connection.cursor() as cursor:
        cursor.execute(user_info_sql)
        if cursor.rowcount > 0:
            result = cursor.fetchone()
            user_info = dict(zip([desc[0] for desc in cursor.description],result))
            article_info["author"] = user_info["name"]
        else:
            return Response({"state":"The user of id=%d doesn't exist!"%user_id})

    # ---- 原创文章梳理和阅读总数----
    temp = articles_of_user(user_id)
    user_info["readNumTotal"]=temp["read_num_total"]
    user_info["originalArticleNum"]=temp["original_article_num"]
    latest_articles = temp["articles"][:6] if len(temp["articles"]) >6 else temp["articles"]

    # ----- 数据整理 -------
    data["articleInfo"] = article_info
    data["authorInfo"] = user_info
    data["latestArticles"] = latest_articles

    return Response(data)